<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';
import {
  Form,
  FormItem,
  InputNumber,
  TimePicker,
  CheckboxGroup,
  Select,
  Divider,
  Space,
} from 'ant-design-vue';
import { useBeforeCloseDiff } from '#/utils/popup';
import type {
  ExerciseConfigForm,
  PlanConfigVO,
} from '#/api/healthPlan/config/planConfig/model';
import {
  planConfigInfo,
  planConfigUpdate,
} from '#/api/healthPlan/config/planConfig';
import type { CheckboxValueType } from 'ant-design-vue/es/checkbox/interface';

const emit = defineEmits<{ reload: [] }>();

const title = '运动方案配置';
const taskData = ref<PlanConfigVO | null>(null);

// 定义表单的默认值，字段与后端Vo对应
const getDefaultValues = (): ExerciseConfigForm => ({
  name: undefined,
  exerciseTypes: [],
  aerobicFrequencyUnit: 'PER_WEEK',
  aerobicTotalMinutes: undefined,
  aerobicTargetHeartRate: undefined,
  resistanceFrequencyUnit: 'PER_WEEK',
  resistanceFrequencyTimes: undefined,
  resistanceDurationMinutes: undefined,
  mindBodyFrequencyUnit: 'PER_WEEK',
  mindBodyFrequencyTimes: undefined,
  mindBodyDurationMinutes: undefined,
  reminderTime: undefined,
});

const formData = ref<ExerciseConfigForm>(getDefaultValues());

// 动态校验规则
const formRules = computed<
  Partial<Record<keyof ExerciseConfigForm, RuleObject[]>>
>(() => {
  const rules: Partial<Record<keyof ExerciseConfigForm, RuleObject[]>> = {
    exerciseTypes: [{ required: true, message: '请至少选择一种运动类型' }],
    reminderTime: [{ required: true, message: '请选择提醒时间' }],
  };

  if (formData.value.exerciseTypes.includes('AEROBIC')) {
    rules.aerobicTotalMinutes = [{ required: true, message: '请输入总时长' }];
  }
  if (formData.value.exerciseTypes.includes('RESISTANCE')) {
    rules.resistanceFrequencyTimes = [
      { required: true, message: '请输入频率次数' },
    ];
    rules.resistanceDurationMinutes = [
      { required: true, message: '请输入每次时长' },
    ];
  }
  if (formData.value.exerciseTypes.includes('MIND_BODY')) {
    rules.mindBodyFrequencyTimes = [
      { required: true, message: '请输入频率次数' },
    ];
    rules.mindBodyDurationMinutes = [
      { required: true, message: '请输入每次时长' },
    ];
  }

  return rules;
});

const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);

const handleTypeChange = (currentTypes: CheckboxValueType[]) => {
  const allTypes = ['AEROBIC', 'RESISTANCE', 'MIND_BODY'];
  const deselectedTypes = allTypes.filter(
    (type) => !currentTypes.includes(type),
  );

  deselectedTypes.forEach((type) => {
    if (type === 'AEROBIC') {
      formData.value.aerobicFrequencyUnit = 'PER_WEEK';
      formData.value.aerobicTotalMinutes = undefined;
      formData.value.aerobicTargetHeartRate = undefined;
    }
    if (type === 'RESISTANCE') {
      formData.value.resistanceFrequencyUnit = 'PER_WEEK';
      formData.value.resistanceFrequencyTimes = undefined;
      formData.value.resistanceDurationMinutes = undefined;
    }
    if (type === 'MIND_BODY') {
      formData.value.mindBodyFrequencyUnit = 'PER_WEEK';
      formData.value.mindBodyFrequencyTimes = undefined;
      formData.value.mindBodyDurationMinutes = undefined;
    }
  });
};

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: () => JSON.stringify(formData.value),
    currentGetter: () => JSON.stringify(formData.value),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[700px]',
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) return;
    modalApi.modalLoading(true);
    const record = modalApi.getData() as PlanConfigVO;
    taskData.value = await planConfigInfo(record.id);
    if (taskData.value && taskData.value.taskConfig) {
      // 直接将后端的taskConfig合并到默认值上，完成回显
      formData.value = { ...getDefaultValues(), ...taskData.value.taskConfig };
    }
    await markInitialized();
    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    await validate();
    const dataToSubmit = {
      ...taskData.value,
      taskConfig: cloneDeep(formData.value),
      // 触发时间配置
      triggerConfig: {
        // 每日触发
        dailyTrigger: true,
      },
    };
    await planConfigUpdate(dataToSubmit);
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

function handleClosed() {
  resetFields();
  formData.value = getDefaultValues();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title">
    <Form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <FormItem label="运动类型" v-bind="validateInfos.exerciseTypes">
        <CheckboxGroup
          v-model:value="formData.exerciseTypes"
          :options="[
            { label: '有氧运动', value: 'AEROBIC' },
            { label: '抗阻运动', value: 'RESISTANCE' },
            { label: '身心运动', value: 'MIND_BODY' },
          ]"
          @change="handleTypeChange"
        />
      </FormItem>

      <!-- 有氧运动配置 -->
      <div v-if="formData.exerciseTypes.includes('AEROBIC')">
        <Divider>有氧运动</Divider>
        <FormItem label="运动频率" v-bind="validateInfos.aerobicTotalMinutes">
          <Space.Compact>
            <Select
              v-model:value="formData.aerobicFrequencyUnit"
              class="w-[80px]"
            >
              <Select.Option value="PER_WEEK">每周</Select.Option>
              <Select.Option value="PER_DAY">每天</Select.Option>
            </Select>
            <InputNumber
              v-model:value="formData.aerobicTotalMinutes"
              :min="1"
              addon-after="分钟"
            />
          </Space.Compact>
        </FormItem>
        <FormItem
          label="运动心率"
          v-bind="validateInfos.aerobicTargetHeartRate"
        >
          <InputNumber
            v-model:value="formData.aerobicTargetHeartRate"
            addon-after="次/分钟"
          />
        </FormItem>
      </div>

      <!-- 抗阻运动配置 -->
      <div v-if="formData.exerciseTypes.includes('RESISTANCE')">
        <Divider>抗阻运动</Divider>
        <FormItem
          label="运动频率"
          v-bind="validateInfos.resistanceFrequencyTimes"
        >
          <Space.Compact>
            <Select
              v-model:value="formData.resistanceFrequencyUnit"
              class="w-[80px]"
            >
              <Select.Option value="PER_WEEK">每周</Select.Option>
              <Select.Option value="PER_DAY">每天</Select.Option>
            </Select>
            <InputNumber
              v-model:value="formData.resistanceFrequencyTimes"
              :min="1"
              addon-after="次"
            />
          </Space.Compact>
        </FormItem>
        <FormItem
          label="运动时间"
          v-bind="validateInfos.resistanceDurationMinutes"
        >
          <InputNumber
            v-model:value="formData.resistanceDurationMinutes"
            addon-after="分钟/次"
          />
        </FormItem>
      </div>

      <!-- 身心运动配置 -->
      <div v-if="formData.exerciseTypes.includes('MIND_BODY')">
        <Divider>身心运动</Divider>
        <FormItem
          label="运动频率"
          v-bind="validateInfos.mindBodyFrequencyTimes"
        >
          <Space.Compact>
            <Select
              v-model:value="formData.mindBodyFrequencyUnit"
              class="w-[80px]"
            >
              <Select.Option value="PER_WEEK">每周</Select.Option>
              <Select.Option value="PER_DAY">每天</Select.Option>
            </Select>
            <InputNumber
              v-model:value="formData.mindBodyFrequencyTimes"
              :min="1"
              addon-after="次"
            />
          </Space.Compact>
        </FormItem>
        <FormItem
          label="运动时间"
          v-bind="validateInfos.mindBodyDurationMinutes"
        >
          <InputNumber
            v-model:value="formData.mindBodyDurationMinutes"
            addon-after="分钟/次"
          />
        </FormItem>
      </div>

      <Divider />

      <FormItem label="提醒时间" v-bind="validateInfos.reminderTime">
        <TimePicker
          v-model:value="formData.reminderTime"
          class="w-full"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
        />
      </FormItem>
    </Form>
  </BasicModal>
</template>
